<!-- 示例: 禁止插入重复元素 -->
<template>
  <div class="container">
    <draggable :list="arr" :group="{name:'test',pull:'clone'}" animation="300" class="draggablePanel" :move="onMove"
               @end="onEnd">
      <transition-group>
        <div class="item" v-for="item in arr" :key="item.id">{{ item.name }}</div>
      </transition-group>
    </draggable>
    <draggable :list="arr2" group="test" animation="300" class="draggablePanel">
      <transition-group>
        <div class="item" v-for="item in arr2" :key="item.id">{{ item.name }}</div>
      </transition-group>
    </draggable>
  </div>
</template>

<script>
import {defineComponent, reactive, ref} from "vue";
import {VueDraggableNext as draggable} from 'vue-draggable-next'

export default defineComponent({
  setup() {
    const arr = reactive([
      {id: 1, name: "张三(不允许拖拽)"},
      {id: 2, name: "李四"},
      {id: 3, name: "王五"},
      {id: 4, name: "赵六"}
    ]);
    const arr2 = reactive([]);
    // 记录当前拖拽元素的id
    const moveId = ref(null);
    const onMove = (e, originalEvent) => {
      console.log('onMove', e.draggedContext)
      if (e.draggedContext && e.draggedContext.element && e.draggedContext.element.id == 1) {
        moveId.value = e.draggedContext.element.id
        // 拖拽元素为1, 则禁止拖拽
        return false;
      }
      // 记录当前拖拽元素的id
      moveId.value = e.draggedContext.element.id
      return true;
    }
    const onEnd = (e) => {
      // console.log(e)
      console.log('end', e)
      const tmpArr = arr2.filter(item => {
        // 查找与当前元素相同的元素
        return item.id === moveId.value
      })
      if (tmpArr.length > 1 && e.newDraggableIndex >= 0) {
        // 存在与当前元素相同的元素, 则删除当前元素
        arr2.splice(e.newDraggableIndex, 1)
      }
    }
    return {arr, arr2, onMove, onEnd}
  },
  components: {
    draggable
  }
})
</script>

<style scoped>
.container {
  width: 100%;
}

.draggablePanel {
  box-sizing: border-box;
  height: 300px;
  width: 50%;
  float: left;
  border: 1px solid #eee;
}

.draggablePanel div {
  width: 100%;
  height: 30px;
  line-height: 30px;
  margin-bottom: 5px;
  background-color: #eeeeee;
  padding-left: 20px;
  cursor: move;
}
</style>
